package com.android.basiclib.engine.network

import com.android.basiclib.base.BaseRetrofitClient
import com.android.basiclib.base.vm.BaseRepository
import com.android.basiclib.bean.BaseBean
import com.android.basiclib.bean.OkResult
import com.android.basiclib.bean.Optional
import com.android.basiclib.core.BaseLibCore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.io.IOException

/**
 * 引擎类
 * 网络请求的封装
 */

//可用引擎切换 - 默认用于 Retrofit + suspend方式
suspend fun <T : Any> BaseRepository.httpRequest(call: suspend () -> BaseBean<T>): OkResult<T> {

    return try {

        val response = withContext(Dispatchers.IO) {
            withTimeout(BaseRetrofitClient.TIME_OUT * 1000L) {
                call()
            }
        }

        if (response.code == BaseLibCore.successCode) {

            if (response.data == null) {
                //如果为空，就构造一个空的对象
                OkResult.Error(RuntimeException("data为空"))
            } else {
                OkResult.Success(response.data)
            }

        } else {
            OkResult.Error(IOException(response.message))
        }

    } catch (e: Exception) {

        e.printStackTrace()
        OkResult.Error(handleExceptionMessage(e))
    }

}

/**
 * 处理Data为null，走成功的回调
 */
suspend fun <T : Any> BaseRepository.httpRequestOptional(call: suspend () -> BaseBean<T>): OkResult<Optional<T>> {

    return try {

        val response = call()

        if (response.code == BaseLibCore.successCode) {

            OkResult.Success(response.transform())

        } else {
            OkResult.Error(IOException(response.message))
        }

    } catch (e: Exception) {

        e.printStackTrace()
        OkResult.Error(handleExceptionMessage(e))
    }

}
